package com.hd.crdao.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.hd.crdao.R;
import com.hd.crdao.base.BaseActivity;
import com.hd.crdao.bean.DomainAlipayBean;
import com.hd.crdao.bean.WeixinPayBean;
import com.hd.crdao.config.Constants;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.PayResult;
import com.hd.crdao.utils.SPUtils;
import com.hd.crdao.utils.UIUtils;
import com.hd.crdao.view.ExpandHeadView;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 *
 *@author Administrator
 *@date 2017/7/4 0004
 */
public class OrderCheckActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener{
    @BindView(R.id.user_agreement_head)
    ExpandHeadView mUserAgreementHead;
    @BindView(R.id.domaim)
    TextView mDomaim;
    @BindView(R.id.domain_price)
    TextView mDomainPrice;
    @BindView(R.id.cb_alipay)
    CheckBox mCbAlipay;
    @BindView(R.id.rl_alipay)
    RelativeLayout mRlAlipay;
    @BindView(R.id.cb_weixin)
    CheckBox mCbWeixin;
    @BindView(R.id.rl_weixin)
    RelativeLayout mRlWeixin;
    @BindView(R.id.gopay)
    Button mGopay;
    public double mDomainPrice1;

    //商户APP工程中引入微信JAR包，调用API前，需要先向微信注册您的APPID，代码如下
    final IWXAPI msgApi = WXAPIFactory.createWXAPI(UIUtils.getContext(), null);

    public String mPlOrder;   //确认订单后的订单号
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    /**
     *支付宝支付的回调
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        Toast.makeText(OrderCheckActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        Intent i = new Intent(UIUtils.getContext(),PaySuccessActivity.class);
                        i.putExtra("domainPrice",mDomainPrice1+"");
                        i.putExtra("payType","支付宝");
                        startActivity(i);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(OrderCheckActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
            }
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_ordercheck;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
    }

    @Override
    protected void initListener() {
        mUserAgreementHead.getLeftArrowLL().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               onBackPressed();
            }
        });

        mCbAlipay.setOnCheckedChangeListener(this);
        mCbWeixin.setOnCheckedChangeListener(this);
    }

    @Override
    protected void initData() {
        String busnissId = SPUtils.getString("busnissId", "");
        String domainName = getIntent().getStringExtra("domainName");
        mDomainPrice1 = getIntent().getDoubleExtra("domainPrice", 0.01);
        String id = getIntent().getStringExtra("id");
        mPlOrder = getIntent().getStringExtra("plOrder");
        mDomaim.setText(domainName);
        mDomainPrice.setText("￥"+ mDomainPrice1);
    }

    @OnClick(R.id.gopay)
    public void onViewClicked() {
        showPayPopWindow();
    }
    /**
     * 弹出支付的popwindow
     */
    private void showPayPopWindow() {
        View parent = ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
        View popView = View.inflate(this, R.layout.pop_pay, null);
        ImageView imageView = (ImageView) popView.findViewById(R.id.dissmis);
        TextView payType = (TextView) popView.findViewById(R.id.paytype);
        TextView tvPrice = (TextView) popView.findViewById(R.id.price);
        Button btnPay = (Button) popView.findViewById(R.id.pay);
        if(mCbAlipay.isChecked()){
            payType.setText("支付宝支付");
        }else {
            payType.setText("微信支付");
        }
        tvPrice.setText("￥"+mDomainPrice1);
        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;
        final PopupWindow popWindow = new PopupWindow(popView, width, height);
        popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);
        ColorDrawable dw = new ColorDrawable(0x30000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        //设置监听
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });

        btnPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mCbAlipay.isChecked()){    //如果是选择的支付宝支付
                    toAlipay();
                    popWindow.dismiss();
                }else {
                    if (! msgApi.isWXAppInstalled()) {
                        MyToast.show("请前往应用商店下载微信");
                    } else if (!msgApi.isWXAppSupportAPI()) {
                        MyToast.show("当前版本微信不支持支付");
                    }else {
                        toWeixinPay();
                        popWindow.dismiss();
                    }
                }
            }
        });

    }

    /**
     * 请求接口,跳转到微信支付
     */
    private void toWeixinPay() {
        OkHttpUtils.post().url(Constants.DOMAIN_PAY_UTL).addParams("orderId",mPlOrder).addParams("type","WX").addParams("money",mDomainPrice1+"")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("请求失败,请检查网络...");
            }

            @Override
            public void onResponse(String response, int id) {
                ALog.d(response);
                Gson gson = new Gson();
                WeixinPayBean weixinPayBean = gson.fromJson(response, WeixinPayBean.class);
                String message = weixinPayBean.getMessage();
                String success = weixinPayBean.getSuccess();
                if(TextUtils.equals("00",success)){
                    SPUtils.saveString("domainPayinfo",mDomainPrice1+"");
                    WeixinPayBean.RowsBean rows = weixinPayBean.getRows();
                    ALog.d("appId="+rows.getAppid());
                    ALog.d("partnerId="+rows.getPartnerid());
                    ALog.d("prepayId="+rows.getPrepayid());
                    ALog.d("packageValue="+rows.getPackageX());
                    ALog.d("nonceStr="+rows.getNoncestr());
                    ALog.d("timeStamp="+String.valueOf(rows.getTimestamp()));
                    ALog.d("sign="+rows.getSign());
                    //调起支付
                    PayReq request = new PayReq();
                    request.appId = rows.getAppid();
                    request.partnerId = rows.getPartnerid();
                    request.prepayId= rows.getPrepayid();
                    request.packageValue = rows.getPackageX();
                    request.nonceStr=rows.getNoncestr();
                    request.timeStamp= String.valueOf(rows.getTimestamp());
                    request.sign= rows.getSign();
                    // 将该app注册到微信
                    msgApi.registerApp(Constants.APP_ID);
                    msgApi.sendReq(request);

                }else {
                    MyToast.show(message);
                }
            }
        });
    }

    /**
     * 请求接口,跳转到支付宝支付
     */
    private void toAlipay() {
        OkHttpUtils.post().url(Constants.DOMAIN_PAY_UTL).addParams("orderId",mPlOrder).addParams("type","ZFB").addParams("money",mDomainPrice1 + "")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("请求失败,请检查网络...");
            }

            @Override
            public void onResponse(String response, int id) {
                ALog.d(response);
                Gson gson = new Gson();
                DomainAlipayBean domainAlipayBean = gson.fromJson(response, DomainAlipayBean.class);
                String message = domainAlipayBean.getMessage();
                String success = domainAlipayBean.getSuccess();
                if (TextUtils.equals("00", success)) {
                    final String orderInfo = domainAlipayBean.getOrderId();   // 订单信息
                    Runnable payRunnable = new Runnable() {

                        @Override
                        public void run() {
                            PayTask alipay = new PayTask(OrderCheckActivity.this);
                            Map<String, String> result = alipay.payV2(orderInfo,true);
                            Message msg = new Message();
                            msg.what = SDK_PAY_FLAG;
                            msg.obj = result;
                            mHandler.sendMessage(msg);
                        }
                    };
                    // 必须异步调用
                    Thread payThread = new Thread(payRunnable);
                    payThread.start();
                } else {
                    MyToast.show(message);
                }
            }
        });
    }

    /**
     * checkbox的监听器
     */
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.cb_alipay:
                if (isChecked) {
                    mCbAlipay.setChecked(true);
                    mCbWeixin.setChecked(false);
                }
                break;
            case R.id.cb_weixin:
                if (isChecked) {
                    mCbWeixin.setChecked(true);
                    mCbAlipay.setChecked(false);
                }
                break;
        }
    }

    @Override
    public void onBackPressed() {
        startActivity(new Intent(UIUtils.getContext(),MyShopActivity.class));
        finish();
    }
}
